<template>
  <el-dialog title="查看/编辑片区信息"
             :close-on-click-modal="false"
             :visible.sync="visible"
             @close="close"
             width="70%">
    <div>
      <el-form label-width="120px" :model="dataForm" :rules="dataRule" ref="dataForm" :inline="true"  @keyup.enter.native="dataFormSubmit()">
        <el-form-item label="片区名称：" prop="name">
          <el-input v-model="dataForm.name" placeholder="片区名称"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="regionId">
          <el-cascader
            style="width: 300px"
            @change="changeArea"
            v-model="dataForm.regionId"
            :options="options"
            :props="props"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item label="经度" prop="latitude">
          <el-input v-model="dataForm.latitude" placeholder="请输入经度"></el-input>
        </el-form-item>
        <el-form-item label="纬度" prop="longitude">
          <el-input v-model="dataForm.longitude" placeholder="请输入纬度"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="dataForm.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <div id="container-map" class="map"></div>
        <el-form-item class="footer">
          <el-button type="primary" @click.stop="dataFormSubmit" size="small">提交</el-button>
          <el-button type="primary" plain @click.stop="close" size="small">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
  import AMap from 'AMap'
  import { isMobile } from '@/utils/validate'
  export default {
    name: 'addDistrictOrUpdate',
    data () {
      return {
        map: '',
        visible: false,
        dataForm: {
          id: '',
          name: '',
          regionId: '',
          latitude: '',
          longitude: '',
          address: '',
          status: 1
        },
        options: [],
        props: {
          multiple: false,
          label: 'name',
          value: 'id',
          children: 'childs'
        },
        dataRule: {
          name: [
            { required: true, message: '片区名称不能为空', trigger: 'blur' }
          ],
          regionId: [
            { required: true, message: '所在地区不能为空', trigger: 'blur' }
          ],
          address: [
            { required: true, message: '详细地址不能为空', trigger: 'blur' }
          ]
        }
      }
    },

    mounted(){
    },

    methods: {
      init (id) {
        this.dataForm.id = id
        this.visible = true
        this.$http({
          url: this.$http.adornUrl('/v1/merchant/charging/group/detail'),
          method: 'get',
          params: this.$http.adornParams({id: this.dataForm.id})
        }).then(({ data }) => {
          this.dataForm = data.data
          console.log(this.dataForm)
          let center = [this.dataForm.longitude, this.dataForm.latitude]
          this.$nextTick(() => {
            this.initMap(center)
          })
        })
        this.getAreaList()
      },

      initMap (center) {
        let _this = this
        var map = new AMap.Map('container-map', {
          center: center, // [纬度，经度]
          resizeEnable: true,
          viewMode: '2D',
          zoom: 10
        })

        let marker = new AMap.Marker({
          position: center,
          offset: new AMap.Pixel(-13, -30)
        });
        map.add(marker); //加载点

        map.on("click", showInfoClick);
        function showInfoClick(e) {
          map.clearMap();//清理地图
          let lng = e.lnglat.getLng()
          let lat = e.lnglat.getLat()
          regeocoder([lng, lat], _this)
          //marker点
          let marker = new AMap.Marker({
            position: [lng, lat],
            offset: new AMap.Pixel(-13, -30)
          })
          _this.dataForm.longitude = lng
          _this.dataForm.latitude = lat
          map.add(marker)
        }

        var geocoder;
        function regeocoder(lnglatXY,that) {
          AMap.plugin('AMap.Geocoder',function(){
            var geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: "all"
            })
            geocoder.getAddress(lnglatXY, function(status, result) {
              if (status === 'complete' && result.info === 'OK') {
                that.getAreaIdByCode(result.regeocode.addressComponent.adcode)
                var address = result.regeocode.formattedAddress;
                that.dataForm.address = address
              }
            })
          })
        }

        AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function () {
          map.addControl(new AMap.ToolBar())

          map.addControl(new AMap.Scale())
        })
        this.map = map
      },


      getAreaIdByCode (areaCode) {
        this.$http({
          url: this.$http.adornUrl('/v1/merchant/system/get/by/area/code'),
          method: 'get',
          params: this.$http.adornParams({areaCode: areaCode})
        }).then(({ data }) => {
          this.dataForm.regionId = data.data.id
        })
      },

      changeArea (e) {
        var province = this.options.find((item) => {
          return item.id == e[0]
        })
        var city = province.childs.find((item) => {
          return item.id == e[1]
        })
        var district = city.childs.find((item) => {
          return item.id == e[2]
        })
        this.dataForm.address = `${province.name}${city.name}${district.name}`
        console.log(city)
        this.getLocation(this.dataForm.address, city.code, this.map)
      },

      getLocation (searchArea, cityCode, map) {
        const _this = this
        AMap.plugin('AMap.Geocoder',function(){
          map.clearMap()
          let geocoder = new AMap.Geocoder({
            city: cityCode
          })
          geocoder.getLocation(searchArea, function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // result中对应详细地理坐标信息
              let lng = result.geocodes[0].location.lng
              let lat = result.geocodes[0].location.lat
              _this.dataForm.longitude = lng
              _this.dataForm.latitude = lat
              map.setCenter([lng, lat])
              let marker = new AMap.Marker({
                map: map,
                position: [lng, lat],
                offset: new AMap.Pixel(-13, -30)
              })
              map.add(marker)
            }
          })
        })
      },

      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl('/v1/merchant/charging/group/update'),
              method: 'post',
              data: this.$http.adornData(this.dataForm)
            }).then(({ data }) => {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList', this.page)
                }
              })
            })
          }
        })
      },

      getAreaList () {
        this.$http({
          url: this.$http.adornUrl('/v1/merchant/system/get/all/region'),
          method: 'get',
          params: this.$http.adornParams({})
        }).then(({ data }) => {
          this.options = data.data
        })
      },

      close () {
        this.$refs['dataForm'].resetFields()
        this.visible = false
      }
    }
  }
</script>

<style lang="scss" scoped>
  .footer{
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .map{
    height: 400px;
    width: 100%;
  }

  .el-input{
    width: 300px;
  }
</style>
